import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { DetectionHistory } from '../entity/DetectionHistory';

interface CreateDetectionParams {
  userId: string;
  originalImageUrl: string;
  resultImage: string;
  ratio: number;
  diagnosis: string;
  filename: string;
  fileSize: number;
}

@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class DetectionDao {
  @InjectEntityModel(DetectionHistory)
  historyModel: Repository<DetectionHistory>;

  // 关键功能：创建检测历史记录
  async create(userId: string, imageUrl: string): Promise<number> {
    const entity = this.historyModel.create({ userId, imageUrl });
    const saved = await this.historyModel.save(entity);
    return saved.id;
  }

  // 新功能：创建详细的AI检测记录
  async createWithDetails(params: CreateDetectionParams): Promise<{ id: number; createdAt: Date }> {
    const entity = this.historyModel.create({
      userId: params.userId,
      originalImageUrl: params.originalImageUrl,
      resultImage: params.resultImage,
      ratio: params.ratio,
      diagnosis: params.diagnosis,
      filename: params.filename,
      fileSize: params.fileSize,
      imageUrl: params.originalImageUrl // 兼容性字段
    });
    const saved = await this.historyModel.save(entity);
    return {
      id: saved.id,
      createdAt: saved.detectedAt
    };
  }

  // 关键功能：分页获取用户检测历史
  async list(userId: string, page: number, pageSize: number): Promise<{ list: DetectionHistory[]; total: number }> {
    const [list, total] = await this.historyModel.findAndCount({
      where: { userId },
      order: { detectedAt: 'DESC' },
      skip: (page - 1) * pageSize,
      take: pageSize,
      select: ['id', 'imageUrl', 'detectedAt', 'status', 'userId'],
    });
    return { list, total };
  }

  // 关键功能：按ID删除用户的检测历史记录（只允许删除自己的记录）
  async delete(userId: string, id: number): Promise<boolean> {
    const result = await this.historyModel.delete({ id, userId });
    return !!result.affected && result.affected > 0;
  }
}